iT邦幫忙

2022 iThome 鐵人賽

DAY 23
0
Mobile Development

Android studio 30天新手筆記系列 第 23

Day23-Android新手筆記-Fragment基本介紹

  • 分享至 

  • xImage
  •  

一個Activity中可以嵌入多個Fragment,Fragment具有自己的生命週期,可以處理自己的事件,但是它不能單獨存在,必須依附在Activityc或另一個Fragment上。善用Fragment可以方便實現不同布局,增加畫面的層次結構。

/images/emoticon/emoticon31.gif

Fragment

activity_main布局

加入FrameLayout容器與兩個Button實現Fragment切換

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_changeA"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

    <Button
        android:id="@+id/btn_changeA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginBottom="50dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btn_changeB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="50dp"
        android:layout_marginBottom="50dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

建立兩個Fragment(FragmentA、FragmentB)



fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentA">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="FragmentA" />

</FrameLayout>

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentB">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="FragmentB" />

</FrameLayout>

FragmentA.Java

public class FragmentA extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public FragmentA() {

    }

    public static FragmentA newInstance(String param1, String param2) {
        FragmentA fragment = new FragmentA();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }
}

FragmentB.Java

public class FragmentB extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public FragmentB() {

    }

    public static FragmentB newInstance(String param1, String param2) {
        FragmentB fragment = new FragmentB();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b, container, false);
    }
}

於activity_main.java綁定Fragment與Button點擊切換

public class MainActivity extends AppCompatActivity {

    private Button btn_changeA,btn_changeB;
    private FragmentA fragmentA;
    private FragmentB fragmentB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_changeA = findViewById(R.id.btn_changeA);
        btn_changeB = findViewById(R.id.btn_changeB);
        fragmentA = new FragmentA();
        fragmentB = new FragmentB();

        //獲取FragmentManager使用beginTransaction(),對關聯的Fragment進行一系列編輯操作
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout,fragmentA,"A").commit();

        btn_changeA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //replace()方法,用於切換Fragment。須注意並不會保存上一個Fragment。
                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragmentA,"A").commit();
            }
        });
        btn_changeB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //replace()方法,用於切換Fragment。須注意並不會保存上一個Fragment。
                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragmentB,"B").commit();
            }
        });
    }
}

透過FragmentManager與FragmentTransaction對關聯的Fragment進行一系列如添加、移除、替換等編輯操作。這邊有使用到add()與replace()方法
,其中replace()方法需特別注意當從FragmentA切換過去FragmentB時,並不會保存FragmentA的狀態。

/images/emoticon/emoticon41.gif


上一篇
Day22-Android新手筆記-BottomNavigationView基本介紹
下一篇
Day24-Android新手筆記-ViewPage2基本介紹
系列文
Android studio 30天新手筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言